import { Button, Col, Flex, Form, Input, Modal, ModalProps, Row, Space, Table } from "antd";
import { memo, useEffect, useState } from "react";
import { ISqUnit, useAddSqUnit, useDeleteSqUnit, useGetSqUnit, useUpdateSqUnit } from "../../../service/unit-service";
import { BaseContiner, TableContainer, TableHeader } from "../../../csscomponents/base";
import { ErrorBox } from "../../../components/error-box";
import {
    PlusOutlined,
    SearchOutlined
} from '@ant-design/icons';
import { useForm } from "antd/es/form/Form";
type SqForm = {
    open: boolean;
    setOpen: (open: boolean) => void;
    unitId?: string | undefined;
} & ModalProps

const SqForm = ({ open, setOpen, unitId }: SqForm) => {

    const [queryForm] = useForm();
    const [sequFrom] = useForm();
    const [formOpen, setFormOpen] = useState<boolean>();
    const [updateSqUnit, setUpdateSqUnit] = useState<ISqUnit>();
    const [queryParams, setQueryParams] = useState<{
        unitId: string;
        sqUnitName: string;
    }>({
        unitId: "",
        sqUnitName: ""
    });

    useEffect(() => {
        if (unitId) {
            setQueryParams({
                unitId,
                sqUnitName: ""
            });
        }
    }, [unitId])

    /**搜索单位 */
    const searchData = (value: { sqUnitName: string }) => {
        setQueryParams({
            ...queryParams,
            sqUnitName: value.sqUnitName,
        });
    };
    /**
   * 重置搜索
   */
    const resetQueryParams = () => {
        setQueryParams({
            unitId: "",
            sqUnitName: ""
        });
        queryForm.resetFields();
    }

    /**
     *!社区HOOK
     */
    const { mutateAsync: deleteMutation, isLoading: DIsLoading } = useDeleteSqUnit();
    /**
     *!获取社区HOOK
     */
    const { isLoading, isError, data: dataSource, error, refetch } = useGetSqUnit(queryParams);

    /**
    * !添加社区Hook
    */
    const { mutateAsync: addMutation, isLoading: addIsLoading } = useAddSqUnit();
    /**
     * !修改社区Hook
     */
    const { mutateAsync: updateMutation, isLoading: UIsLoading } = useUpdateSqUnit();

    /**删除社区 */
    const removeUnitHandler = (sqUnitId: string) => {
        Modal.confirm({
            title: '⚠️警告',
            content: '你确认执行改操作吗?',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                await deleteMutation({ sqUnitId });
                refetch();
            },
        });
    };

    /**
     * 修改社区
     * @param sqUnitId 社区ID
     */
    const updateHandler = (project: ISqUnit) => {
        setUpdateSqUnit(project);
        setFormOpen(true)
    }
    const columns = [
        {
            title: '社区名称',
            dataIndex: 'sqUnitName',
        },
        {
            title: '更多操作',
            render(project: ISqUnit) {
                return (
                    <div>
                        <Button style={{ marginRight: '1.2rem' }} onClick={() => updateHandler(project)}>
                            修改
                        </Button>
                        <Button loading={DIsLoading} danger onClick={() => removeUnitHandler(project.sqUnitId)}>
                            删除
                        </Button>
                    </div>
                );
            },
        },
    ];

    //提交表单
    const okSqFormHandler = async () => {
        if (updateSqUnit) {
            //更新
            const isPass = sequFrom.validateFields();
            if (!isPass) {
                return;
            }
            const values = await sequFrom.getFieldsValue();
            await updateMutation({ ...values, unitId, sqUnitId: updateSqUnit.sqUnitId });
            refetch?.();
            setFormOpen(false)
            setUpdateSqUnit(undefined);
        } else {
            //添加
            const isPass = sequFrom.validateFields();
            if (!isPass) {
                return;
            }
            const values = await sequFrom.getFieldsValue();
            await addMutation({ ...values, unitId });
            refetch?.();
            setFormOpen(false)
            setUpdateSqUnit(undefined);
        }
    }

    return <Modal
        title="社区"
        centered
        open={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        okText={"确认"}
        cancelText={"取消"}
        width={'600px'}
        styles={{ body: { height: '600px', overflow: 'auto' } }}
    >
        <BaseContiner>
            <TableHeader>
                <Form onFinish={searchData} style={{ width: '100%' }} form={queryForm}>
                    <Row gutter={16}>
                        <Col span={10}>
                            <Form.Item label="社区名称" name={'sqUnitName'}>
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={10}>
                            <Form.Item>
                                <Space>
                                    <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                        搜索
                                    </Button>
                                    <Button type="primary" onClick={() => resetQueryParams()}>
                                        重置
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Flex gap="small" justify="flex-end">
                                <Form.Item>
                                    <Button type={'primary'} icon={<PlusOutlined />} onClick={() => {
                                        setFormOpen(true)
                                    }} >
                                        添加
                                    </Button>
                                </Form.Item>
                            </Flex>
                        </Col>
                    </Row>
                </Form>
            </TableHeader>
            <TableContainer>
                {isError ? (
                    <ErrorBox error={error as { message: string }} />
                ) : (
                    <Table rowSelection={{ type: 'checkbox' }} dataSource={dataSource} columns={columns} loading={isLoading || DIsLoading} rowKey={(row) => row?.sqUnitId} />
                )}
            </TableContainer>
        </BaseContiner>

        <Modal title="社区"
            centered
            open={formOpen}
            onOk={() => okSqFormHandler()}
            onCancel={() => setFormOpen(false)}
            okText={"确认"}
            cancelText={"取消"}
            width={'400px'}>
            <Form style={{ width: '100%' }} form={sequFrom}>
                <Form.Item label="社区名称" name={'sqUnitName'}>
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    </Modal>
}


export default memo(SqForm);